﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// OperateUser 的摘要说明
/// </summary>
public class UserService
{
    public UserService()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    public static void SetUserAuthIn(string loginName, string cookieDomain)
    {
        //设置用户的 cookie 的值
        FormsAuthentication.SetAuthCookie(loginName, false);

        //获取用户的 cookie 
        HttpCookie cookie = FormsAuthentication.GetAuthCookie(loginName, false, FormsAuthentication.FormsCookiePath);

        //给用户的 cookie 的值加上 cookie 的域 和 过期日期
        //向客户端重写同名的 用户 cookie
        FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(cookie.Value);
        FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(1,
            oldTicket.Name,
            oldTicket.IssueDate,
            DateTime.Now.AddMinutes(30),
            oldTicket.IsPersistent,
            oldTicket.UserData,
            FormsAuthentication.FormsCookiePath);
        cookie.Domain = cookieDomain;
        cookie.Value = FormsAuthentication.Encrypt(newTicket);
        HttpContext.Current.Response.Cookies.Add(cookie);

        return;
        //登陆后的网址转向
        string strUrl = string.Empty;
        if (HttpContext.Current.Request.Params["RefUrl"] == null)
        {
            strUrl = HttpContext.Current.Request.Url.ToString().Trim().Replace("Login", "Default");
        }
        else
        {
            strUrl = HttpContext.Current.Request.Params["RefUrl"].Trim();
        }
        HttpContext.Current.Response.Redirect(HttpContext.Current.Server.UrlDecode(strUrl));
    }

    public static void SetAuthOut(string cookieDomain)
    {
        HttpCookie cookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];
        cookie.Domain = cookieDomain;
        cookie.Value = null;
        cookie.Expires = DateTime.Now.AddDays(-1);
        HttpContext.Current.Response.Cookies.Add(cookie);

        FormsAuthentication.SignOut();
    }

    public static string GetCurrentPersonName()
    {
        string idenName = string.Empty;

        if (HttpContext.Current != null && HttpContext.Current.User != null)
        {
            idenName = HttpContext.Current.User.Identity.Name;
        }
        else
        {
            idenName = "";
        }

        return idenName;
    }
}
